package com.fw.system.web.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fw.common.Builder;
import com.fw.common.IdXD;
import com.fw.constant.Constant;
import com.fw.enums.LogsModelEnum;
import com.fw.enums.LogsTypeEnum;
import com.fw.system.web.dao.FwMoneysMapper;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.service.*;
import com.fw.utils.RandomUtils;
import com.fw.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户钱包表 服务实现类
 * </p>
 *
 * @author
 * @since 2021-05-10
 */
@Service
public class FwMoneysServiceImpl extends ServiceImpl<FwMoneysMapper, FwMoneys> implements IFwMoneysService {
    @Autowired
    private IFwUserService userService;

    @Autowired
    private IFwShowService showService;

    @Autowired
    private IFwLogsService logsService;

    @Autowired
    private IdXD idXD;

    @Autowired
    private IFwDisappearGetService disappearGetService;

    @Autowired
    private IFwRuleDatasService ruleDatasService;


    @Autowired
    private IFwUljoinService uljoinService;
    @Autowired
    private IFwIdentityService identityService;
    @Autowired
    private IFwShangjiaService shangjiaService;
    @Autowired
    private IFwLockStorageService lockStorageService;

    @Autowired
    private  IFwCurrencyLogService currencyLogService;
    @Autowired
    private IFwAgentRegionService agentRegionService;
    @Autowired
    private IFwPolService polService;

    /**
     * 返消证  todo 发放消证调用此方法!
     *
     * @param userId    用户编号
     * @param disappear 发放消证数量
     * @param jsonTxt   描述/发放消证原因
     */
    @Override
    public void disappearReturn(String userId, BigDecimal disappear, String jsonTxt) {
        FwUser rootUser = userService.getById(userId);
        //给当前用户发放消证
        if (  disappearReturnParent(userId, null, disappear, jsonTxt, userId)){
            //累加肖证标识数额、
            FwCurrencyLog logCount = currencyLogService.getById("303204408");
            logCount.setLogCount(logCount.getLogCount().add(disappear));
            currencyLogService.updateById(logCount);
            //用来记录用户返消证和原始数量的日志,用来判断是否是每满一千送一个商甲的条件
            FwCurrencyLog currencyLog = new FwCurrencyLog();
            currencyLog = currencyLogService.getOne(Wrappers.<FwCurrencyLog>lambdaQuery()
                    .eq(FwCurrencyLog::getLogType, 1).eq(FwCurrencyLog::getUserId, rootUser.getId()));
            if (currencyLog ==null){
                currencyLog = currencyLogService.getOne(Wrappers.<FwCurrencyLog>lambdaQuery()
                        .eq(FwCurrencyLog::getLogType, 2).eq(FwCurrencyLog::getUserId, rootUser.getId()));
            }
            if (currencyLog==null){
                FwCurrencyLog build = Builder.of(FwCurrencyLog::new).with(FwCurrencyLog::setId, idXD.nextId()).
                        with(FwCurrencyLog::setCreateTime, LocalDateTime.now()).
                        with(FwCurrencyLog::setLogCount, disappear).
                        with(FwCurrencyLog::setInfoFrom, 1).with(FwCurrencyLog::setLogName, "达成vip送商甲阶段").
                        with(FwCurrencyLog::setUserId, userId).with(FwCurrencyLog::setLogType, 1).build();
                currencyLogService.save(build);
            }else{
                currencyLogService.updateById(currencyLog.setLogCount(currencyLog.getLogCount().add(disappear)));
            }


            //是否升级VIP
            identityService.addIdentity(rootUser);
        }


        //发放的消证
        BigDecimal decimal = BigDecimal.ZERO;
        //给当前用户的上级发放消证
        FwUser parentUser = findParent(userId);
        if (parentUser != null) {
            decimal = disappear.multiply(new BigDecimal("0.1"));
            disappearReturnParent(parentUser.getId(), userId, decimal, userService.selectFwUserById(userId).getUserName() + "赠送", userId);

            //给上级的上级发放消证
            FwUser parentTwoUser = findParent(parentUser.getId());
            if (parentTwoUser != null) {
                decimal = decimal.multiply(new BigDecimal("0.5"));
                disappearReturnParent(parentTwoUser.getId(), parentUser.getId(), decimal, parentUser.getUserName() + "赠送", userId);
                //调用递归
                recursion(parentTwoUser, decimal, rootUser);
            }
        }


    }

    /**
     * 递归发放消证
     *
     * @param user
     * @param disappear
     */
    public void recursion(FwUser user, BigDecimal disappear, FwUser rootUser) {
        //获取上级信息
        FwUser parentUser = findParent(user.getId());
        //判空
        if (parentUser != null) {
            //获取该上级应发消证数据
            disappear = disappear.multiply(new BigDecimal("0.5"));//发放消证为上一级的50%
            //判断上级是否可多级得消证
            if (parentUser.getDisappearIsMore().equals(1)) {
                //发放消证
                disappearReturnParent(parentUser.getId(), user.getId(), disappear, rootUser.getUserName() + "赠送", rootUser.getId());
            }
            int i = disappear.compareTo(new BigDecimal("0.001"));//标记
            if (i > 0) {
                //若返佣消证数量大于1,就继续返
                recursion(parentUser, disappear, user);//todo 我觉的这不对之前放的是rootUser 可能应该放user
            }
        }
    }

    /**
     * 给该用户发放消证
     *
     * @param userId
     * @param disappear
     * @param jsonTxt
     */
    @Override
    @Transactional
    public boolean disappearReturnParent(String userId, String childId, BigDecimal disappear, String jsonTxt, String rootUserId) {
        //获取该用户钱包信息
        FwMoneys moneys = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
        BigDecimal moneysDisappear = moneys.getDisappear();//获取该用户的消证余额
        BigDecimal decimal = moneysDisappear.add(disappear);//该用户的消证余额加上发放的消证数量
        moneys.setDisappear(decimal);
        moneys.setUpdateTime(LocalDateTime.now());
        boolean b = updateById(moneys.setShangJia(getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId,userId)).getShangJia()));//写入数据库

                //新增该用户的消证增加记录
                if (jsonTxt.contains("赠送") || StringUtils.isEmpty(childId)) {
                    logsService.saveParentLogs(rootUserId, userId, childId, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.DISAPPEAR_MODEL.getModelName(), jsonTxt, disappear.toString());
                } else {
                    logsService.saveLogs(rootUserId, userId, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.DISAPPEAR_MODEL.getModelName(), jsonTxt, disappear.toString());

                }
                disappearGetService.insetDisappearGet(userId, jsonTxt, disappear);
              return  b;
            }




    /**
     * 商甲满足一定条件锁仓
     *
     * @param userId
     * @param moneysOld
     */
    public void extracted(String userId, FwMoneys moneysOld) {
        FwRuleDatas lockNum = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.SHANGJIA_LOCK_NUMBER));
        if (moneysOld.getShangJia().compareTo(lockNum.getRuleCount()) > -1) {
            //判断是否要锁仓（释放超过24小时的商甲才能锁仓）
            List<FwLogs> shangJiaLtOneDay = logsService.getShangJiaLtOneDay(moneysOld.getUserId());
            BigDecimal val = new BigDecimal("1000");
            BigDecimal subtractOne = moneysOld.getShangJia();
            if (CollectionUtils.isNotEmpty(shangJiaLtOneDay)) {
                FwLogs log = shangJiaLtOneDay.get(0);
                if (new BigDecimal(log.getFormInfo()).compareTo(val) > 0) {
                    subtractOne = moneysOld.getShangJia().subtract(new BigDecimal(log.getFormInfo()));
                }
            }
            if (subtractOne.compareTo(lockNum.getRuleCount()) > -1) {
                BigDecimal lockCount = subtractOne.divide(lockNum.getRuleCount());//拿到锁仓的倍数
                lockCount = lockCount.setScale(0, BigDecimal.ROUND_DOWN);//lockCount不为0时,向下取整
                BigDecimal locks = lockCount.multiply(lockNum.getRuleCount());//拿到锁仓的数量
                for (int i = 0; i < lockCount.intValue(); i++) {
                    FwLockStorage lockStorage = new FwLockStorage();
                    lockStorage.setId(idXD.nextId());//id
                    lockStorage.setLockTime(LocalDateTime.now());//锁仓时间
                    lockStorage.setUserId(moneysOld.getUserId());//用户编号
                    lockStorage.setLockCount(lockNum.getRuleCount());//锁仓数量
                    lockStorage.setNote(lockNum.getRuleCount().toString());//锁仓总量
                    lockStorage.setFlag(Constant.LockStorage.LOCK_ING);//标记为锁仓
                    lockStorage.setReleaseTime(LocalDateTime.now());//释放时间初始化
                    lockStorageService.save(lockStorage);
                }
                //新增日志
                logsService.saveLogs(moneysOld.getUserId(), moneysOld.getUserId(), LogsTypeEnum.MONEY_LOCK.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "锁仓" + locks + "商甲", locks.toString());
                moneysOld.setShangJia(moneysOld.getShangJia().subtract(locks));
                moneysOld.setUpdateTime(LocalDateTime.now());
                moneysOld.setUserId(userId);
                updateById(moneysOld);
            }


            /*BigDecimal lockUnit = moneysOld.getShangJia().divide(lockNum.getRuleCount(), 0, BigDecimal.ROUND_DOWN);
            moneysOld.setShangJia(moneysOld.getShangJia().subtract(lockUnit.multiply(lockNum.getRuleCount())));
            moneysMapper.updateById(moneysOld);
            //锁仓表
            FwLockStorage lockStorage = new FwLockStorage();
            lockStorage.setId(idXD.nextId());
            lockStorage.setUserId(userId);
            lockStorage.setLockCount(lockUnit.multiply(lockNum.getRuleCount()));
            lockStorage.setLockTime(LocalDateTime.now());
            lockStorage.setFlag("0");//0分红1不分红
            lockStorageService.saveOrUpdate(lockStorage);
            getFwLogs(userId, lockUnit.multiply(lockNum.getRuleCount()),LogsTypeEnum.MONEY_LOCK.getTypeName(),LogsModelEnum.SHANG_JIA_MODEL.getModelName(),"客户满足条件商甲锁仓对应锁仓数据id："+lockStorage.getId());//记录操作日志*/
        }
        //技术、管理商甲锁仓
        List<FwUser> listTec = userService.list(Wrappers.<FwUser>lambdaQuery().eq(FwUser::getId,userId).eq(FwUser::getIsAccount, 1));
        if(CollectionUtils.isNotEmpty(listTec)){
            FwUser fwUser = listTec.get(0);

            FwMoneys fwMoneys = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, fwUser.getId()));
            if(fwMoneys.getTecShangjia().compareTo(lockNum.getRuleCount())>-1){
                BigDecimal lockCount = fwMoneys.getTecShangjia().divide(lockNum.getRuleCount());//拿到锁仓的倍数
                lockCount = lockCount.setScale(0, BigDecimal.ROUND_DOWN);//lockCount不为0时,向下取整
                BigDecimal locks = lockCount.multiply(lockNum.getRuleCount());//拿到锁仓的数量
                for (int i = 0; i < lockCount.intValue(); i++) {
                    FwLockStorage lockStorage = new FwLockStorage();
                    lockStorage.setId(idXD.nextId());//id
                    lockStorage.setLockTime(LocalDateTime.now());//锁仓时间
                    lockStorage.setUserId(fwUser.getId());//用户编号
                    lockStorage.setTecLockCount(lockNum.getRuleCount());//锁仓数量
                    lockStorage.setNote(lockNum.getRuleCount().toString());//锁仓总量
                    lockStorage.setFlag(Constant.LockStorage.LOCK_ING);//标记为锁仓
                    lockStorage.setReleaseTime(LocalDateTime.now());//释放时间初始化
                    lockStorageService.save(lockStorage);
                }
                //新增日志
                logsService.saveLogs(userId, fwUser.getId(), LogsTypeEnum.MONEY_LOCK.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "锁仓技术账号" + locks + "技术商甲", locks.toString());
                fwMoneys.setTecShangjia(fwMoneys.getTecShangjia().subtract(locks));
                fwMoneys.setUpdateTime(LocalDateTime.now());
                fwMoneys.setUpdateBy(userId);
                updateById(fwMoneys);
            }
        }
        List<FwUser> listMan = userService.list(Wrappers.<FwUser>lambdaQuery().eq(FwUser::getId,userId).eq(FwUser::getIsAccount, 2));
        if(CollectionUtils.isNotEmpty(listMan)){
            FwUser fwUser = listMan.get(0);
            FwMoneys fwMoneys = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, fwUser.getId()));
            if(fwMoneys.getManShangjia().compareTo(lockNum.getRuleCount())>-1){
                BigDecimal lockCount = fwMoneys.getManShangjia().divide(lockNum.getRuleCount());//拿到锁仓的倍数
                lockCount = lockCount.setScale(0, BigDecimal.ROUND_DOWN);//lockCount不为0时,向下取整
                BigDecimal locks = lockCount.multiply(lockNum.getRuleCount());//拿到锁仓的数量
                for (int i = 0; i < lockCount.intValue(); i++) {
                    FwLockStorage lockStorage = new FwLockStorage();
                    lockStorage.setId(idXD.nextId());//id
                    lockStorage.setLockTime(LocalDateTime.now());//锁仓时间
                    lockStorage.setUserId(fwUser.getId());//用户编号
                    lockStorage.setManLockCount(lockNum.getRuleCount());//锁仓数量
                    lockStorage.setNote(lockNum.getRuleCount().toString());//锁仓总量
                    lockStorage.setFlag(Constant.LockStorage.LOCK_ING);//标记为锁仓
                    lockStorage.setReleaseTime(LocalDateTime.now());//释放时间初始化
                    lockStorageService.save(lockStorage);
                }
                //新增日志
                logsService.saveLogs(userId, fwUser.getId(), LogsTypeEnum.MONEY_LOCK.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "锁仓管理账号" + locks + "管理商甲", locks.toString());
                fwMoneys.setManShangjia(fwMoneys.getManShangjia().subtract(locks));
                fwMoneys.setUpdateTime(LocalDateTime.now());
                fwMoneys.setUpdateBy(userId);
                updateById(fwMoneys);
            }
        }
        //原始商甲账户锁仓
        List<FwUser> listOri = userService.list(Wrappers.<FwUser>lambdaQuery().eq(FwUser::getId,userId).eq(FwUser::getIsAccount, 3));
        if(CollectionUtils.isNotEmpty(listOri)){
            FwUser fwUser = listOri.get(0);
            FwMoneys fwMoneys = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, fwUser.getId()));
            if(fwMoneys.getShangJia().compareTo(lockNum.getRuleCount())>-1){

                //判断是否要锁仓（释放超过24小时的商甲才能锁仓）
                List<FwLogs> shangJiaLtOneDay = logsService.getShangJiaLtOneDay(fwUser.getId());
                BigDecimal val = new BigDecimal("1000");
                BigDecimal subtractOne = fwMoneys.getShangJia();
                if (CollectionUtils.isNotEmpty(shangJiaLtOneDay)) {
                    FwLogs log = shangJiaLtOneDay.get(0);
                    if (new BigDecimal(log.getFormInfo()).compareTo(val) > 0) {
                        subtractOne = fwMoneys.getShangJia().subtract(new BigDecimal(log.getFormInfo()));
                    }
                }
                BigDecimal lockCount = subtractOne.divide(lockNum.getRuleCount());//拿到锁仓的倍数
                lockCount = lockCount.setScale(0, BigDecimal.ROUND_DOWN);//lockCount不为0时,向下取整
                BigDecimal locks = lockCount.multiply(lockNum.getRuleCount());//拿到锁仓的数量
                for (int i = 0; i < lockCount.intValue(); i++) {
                    FwLockStorage lockStorage = new FwLockStorage();
                    lockStorage.setId(idXD.nextId());//id
                    lockStorage.setLockTime(LocalDateTime.now());//锁仓时间
                    lockStorage.setUserId(fwUser.getId());//用户编号
                    lockStorage.setLockCount(lockNum.getRuleCount());//锁仓数量
                    lockStorage.setNote(lockNum.getRuleCount().toString());//锁仓总量
                    lockStorage.setFlag(Constant.LockStorage.LOCK_ING);//标记为锁仓
                    lockStorage.setReleaseTime(LocalDateTime.now());//释放时间初始化
                    lockStorageService.save(lockStorage);
                }
                //新增日志
                logsService.saveLogs(userId, fwUser.getId(), LogsTypeEnum.MONEY_LOCK.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "锁仓原始账号" + locks + "商甲", locks.toString());
                fwMoneys.setShangJia(fwMoneys.getShangJia().subtract(locks));
                fwMoneys.setUpdateTime(LocalDateTime.now());
                fwMoneys.setUpdateBy(userId);
                updateById(fwMoneys);
            }
        }
    }

    /**
     * 根据规则修改商甲数量
     *
     * @param userId
     * @param divide
     * @return
     */
    private FwMoneys getFwMoneys(String userId, BigDecimal divide,String jsonText) {
        //修改用户商甲数量
        FwMoneys moneysOld = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
        FwShangjia consumerSJ = shangjiaService.getOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, Constant.ShangJia.CONSUME_ID));
        consumerSJ.setShopIssue(consumerSJ.getShopIssue().subtract(divide));
        consumerSJ.setUpdateTime(LocalDateTime.now());
        consumerSJ.setUpdateBy(userId);
        moneysOld.setShangJia(moneysOld.getShangJia().add(divide));
        moneysOld.setUpdateTime(LocalDateTime.now());
        moneysOld.setUpdateBy(userId);
        getFwLogs(userId, divide, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), jsonText);//记录操作日志
        shangjiaService.saveOrUpdate(consumerSJ);//修改消费商甲剩余商甲
        updateById(moneysOld);

        //消费商甲每出20个，原始商甲释放出2个，技术释放1个  管理释放1个
        double sumShangJia = logsService.list(Wrappers.<FwLogs>lambdaQuery().eq(FwLogs::getIsType, LogsTypeEnum.MONEY_INCOME).eq(FwLogs::getModelName, LogsModelEnum.SHANG_JIA_MODEL).and(o->o.like(FwLogs::getJsonTxt, "线下消费返消证").or().like(FwLogs::getJsonTxt, "竞猜送消证").or().like(FwLogs::getJsonTxt, "购物送消证"))).stream().mapToDouble(o -> Double.parseDouble(o.getFormInfo())).sum();
        List<FwLogs> listOri = logsService.list(Wrappers.<FwLogs>lambdaQuery().eq(FwLogs::getIsType, LogsTypeEnum.MONEY_RELEASE_ORI).eq(FwLogs::getModelName, LogsModelEnum.SHANG_JIA_MODEL));
        double releaseOri = CollectionUtils.isNotEmpty(listOri) ? listOri.stream().mapToDouble(o -> Double.parseDouble(o.getFormInfo())).sum() : 0l;
        List<FwLogs> listTec = logsService.list(Wrappers.<FwLogs>lambdaQuery().eq(FwLogs::getIsType, LogsTypeEnum.MONEY_RELEASE_TEC).eq(FwLogs::getModelName, LogsModelEnum.SHANG_JIA_MODEL));
        double releaseTec = CollectionUtils.isNotEmpty(listTec) ? listTec.stream().mapToDouble(o -> Double.parseDouble(o.getFormInfo())).sum() : 0l;
        List<FwLogs> listMan = logsService.list(Wrappers.<FwLogs>lambdaQuery().eq(FwLogs::getIsType, LogsTypeEnum.MONEY_RELEASE_MAN).eq(FwLogs::getModelName, LogsModelEnum.SHANG_JIA_MODEL));
        double releaseMan = CollectionUtils.isNotEmpty(listMan) ? listMan.stream().mapToDouble(o -> Double.parseDouble(o.getFormInfo())).sum() : 0l;
        double surplus = sumShangJia - releaseOri * 2 - releaseTec - releaseMan;
        BigDecimal count = new BigDecimal(surplus).divide(new BigDecimal(20), 0, BigDecimal.ROUND_DOWN);
        //获取技术、管理、原始权限人员0 = 普通用户，1= 技术，2= 管理,3=原始
        List<FwUser> list = userService.list(Wrappers.<FwUser>lambdaQuery().eq(FwUser::getIsAccount, 1).or().eq(FwUser::getIsAccount, 2).or().eq(FwUser::getIsAccount, 3));
        HashMap<String, String> map = new HashMap<>();
        for (FwUser user : list) {
            if (user.getIsAccount() == 1) {
                map.put("tecUserId", user.getId());
                continue;
            }
            if (user.getIsAccount() == 2) {
                map.put("manUserId", user.getId());
                continue;
            }
            map.put("oriUserId", user.getId());
        }
        //更新日志
        logsService.saveLogs(userId, map.get("tecUserId"), LogsTypeEnum.MONEY_RELEASE_TEC.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "满足释放技术商甲", count.toString());
        logsService.saveLogs(userId, map.get("manUserId"), LogsTypeEnum.MONEY_RELEASE_MAN.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "满足释放管理商甲", count.toString());
        logsService.saveLogs(userId, map.get("oriUserId"), LogsTypeEnum.MONEY_RELEASE_ORI.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "满足释放原始商甲", count.multiply(new BigDecimal(2)).toString());
        //更新对应人员钱包
        FwMoneys tecUser = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, map.get(map.get("tecUserId"))));
        FwMoneys manUser = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, map.get(map.get("manUserId"))));
        FwMoneys oriUser = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, map.get(map.get("oriUserId"))));
        FwMoneys fwMoneys = new FwMoneys();
        fwMoneys.setCreateBy(userId);
        fwMoneys.setCreateTime(LocalDateTime.now());
        fwMoneys.setUpdateBy(userId);
        fwMoneys.setUpdateTime(LocalDateTime.now());
        if (null != tecUser) {
            tecUser.setTecShangjia(count);
            updateById(tecUser);
        } else {
            fwMoneys.setId(idXD.nextId());
            fwMoneys.setUserId(map.get("tecUserId"));
            fwMoneys.setTecShangjia(count);
            save(fwMoneys);
        }
        if (null != manUser) {
            manUser.setTecShangjia(count);
            updateById(manUser);
        } else {
            fwMoneys.setId(idXD.nextId());
            fwMoneys.setUserId(map.get("manUserId"));
            fwMoneys.setManShangjia(count);
            save(fwMoneys);
        }
        if (null != oriUser) {
            oriUser.setShangJia(oriUser.getShangJia().add(count));
            updateById(oriUser);
        } else {
            fwMoneys.setId(idXD.nextId());
            fwMoneys.setUserId(map.get("tecUserId"));
            fwMoneys.setShangJia(count);
            save(fwMoneys);
        }
        return moneysOld;
    }

    /**
     * 登记数据变更日志
     *
     * @param userId
     * @param divide
     * @param typeName
     * @param modelName
     * @param jsonText
     */
    private void getFwLogs(String userId, BigDecimal divide, String typeName, String modelName, String jsonText) {
        FwLogs fwLogs = new FwLogs();
        fwLogs.setId(idXD.nextId());
        fwLogs.setBuiId(userId);
        fwLogs.setIsType(typeName);
        fwLogs.setModelName(modelName);
        fwLogs.setJsonTxt(jsonText);
        fwLogs.setFormInfo(divide.toString());
        fwLogs.setCreateBy(userId);
        fwLogs.setCreateTime(LocalDateTime.now());
        fwLogs.setUpdateBy(userId);
        fwLogs.setUpdateTime(LocalDateTime.now());
        logsService.saveOrUpdate(fwLogs);//登记商甲增加日志
    }

    /**
     * 根据消费金额产出商甲 todo 每次用户消费调用此方法
     *
     * @param userId
     * @param disappear 发放的消证数量/消费的金额
     */
    @Override
    @Deprecated
    public void disappearOutput(String userId, BigDecimal disappear) {
        //获取用户信息
        FwUser fwUser = userService.selectFwUserById(userId);
        //获取商甲产出的标准
        FwRuleDatas ruleDatas = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.CONSUMPTION_OUTPUT));
        BigDecimal ruleCount = ruleDatas.getRuleCount();
        //判断客户是否首次消费
        FwShow show = showService.getOne(Wrappers.<FwShow>lambdaQuery().eq(FwShow::getUserId, fwUser.getId()));
        if (show == null) {
            //若是首次消费
            //创建临时产出对象
            FwShow fwShow = new FwShow();
            fwShow.setId(idXD.nextId());
            fwShow.setStandard(new BigDecimal("0"));
            fwShow.setUserId(userId);
            showService.save(fwShow);
        }
        //获取当前用户的临时额度
        BigDecimal standard = show.getStandard();
        BigDecimal add = disappear.add(standard);
        BigDecimal divide = add.divide(ruleCount);
        BigDecimal sj = divide.setScale(0, BigDecimal.ROUND_DOWN);//获取到产出的商甲数量,
        BigDecimal multiply = sj.multiply(ruleCount);//获取到本次扣除的额度
        BigDecimal subtract = add.subtract(multiply);//获取到本次需要存储的临时额度
        show.setStandard(subtract);//写入
        showService.updateById(show);
        int i = sj.compareTo(new BigDecimal("0"));
        //若产出的商甲数量不为0
        if (i > 0) {
            //赠送商甲
            FwMoneys moneys = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
            moneys.setShangJia(moneys.getShangJia().add(sj));
            updateById(moneys);
            //写入日志
            logsService.saveLogs(userId, userId, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "消费产出", sj.toString());
        }

    }

    /**
     * 商户反消证， 并且直推 商户的人 根据等级也反消证， 并且不能记录 全局 商甲这块。
     *
     * @param shop          商户对象
     * @param shopDisappear 需要给商户的消证量
     * @param sourceInfo    消证来源
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shopDisappearReturn(FwShop shop, BigDecimal shopDisappear, String sourceInfo,String template) {
        String userId = shop.getUserId();
        shopReturn(shopDisappear, sourceInfo, userId,template);
        // 新增 直接推荐人的 返利比
        FwUser parentUser = userService.getById(userService.getById(userId).getParentId());
       if (Objects.isNull(parentUser)) return;
       //TODO 谢建周 直接忽略
        if ("1259".equals(parentUser.getId())) return;
        // 得到推荐人等级
        FwUljoin userUl = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getUserId, parentUser.getId()).eq(FwUljoin::getIsUse, Constant.IsUsr.IS_USR));
        if (Objects.isNull(userUl)) return;
        FwIdentity identity = identityService.getById(userUl.getIdentityId());
        // 得到身份
        BigDecimal proportion = Constant.ShopRuleData.getOffShopRule().get(identity.getId());
        if (Objects.nonNull(proportion)) {
            // 得到他的比例
            userId = parentUser.getId();
            BigDecimal parentShopDisappear = RandomUtils.mathNumber(proportion, shopDisappear);
            shopReturnParent(parentShopDisappear, sourceInfo, userId, shop.getUserId());
        }
        // 如果 这个直推人是代理，那么就找到这个商户所存在的代理，继续反点 %2

            // 找到该区域商户
            FwPol fwPol = polService.getOne(Wrappers.<FwPol>lambdaQuery().eq(FwPol::getBusId, shop.getId()));
            if (Objects.nonNull(fwPol)){
                FwAgentRegion regionServiceOne = agentRegionService.getOne(Wrappers.<FwAgentRegion>lambdaQuery().eq(FwAgentRegion::getProvince, fwPol.getProvince()).eq(FwAgentRegion::getCity, fwPol.getCity()).eq(FwAgentRegion::getArea, fwPol.getArea()));
                if (Objects.nonNull(regionServiceOne)){
                    //找到该代理
                    FwUser fwUser = userService.getById(regionServiceOne.getUserId());
                    //拿到比例
                    BigDecimal proxyProportion = RandomUtils.mathNumber( Constant.ShopRuleData.getOffShopRule().get("proxy"), shopDisappear);
                    shopReturnParent(proxyProportion, sourceInfo, fwUser.getId(), shop.getUserId());
                }
            }


    }

    private void shopReturn(BigDecimal shopDisappear, String sourceInfo, String userId,String template) {
        FwMoneys shopMoney = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
        shopMoney.setDisappear(shopMoney.getDisappear().add(shopDisappear)).updateD(userId).updateById();
        //新增该商户的消证增加记录
        logsService.saveLogs(userId, userId, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.DISAPPEAR_MODEL.getModelName(), StringUtils.format(template, shopDisappear), shopDisappear.setScale(3).toString());
        disappearGetService.insetDisappearGet(userId, Constant.ShopRuleData.SHOP_COUNT_DIS, shopDisappear);
    }

    private void shopReturnParent(BigDecimal shopDisappear, String sourceInfo, String userId, String childId) {
        FwMoneys shopMoney = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
        shopMoney.setDisappear(shopMoney.getDisappear().add(shopDisappear)).updateD(userId).updateById();
        //新增该商户的消证增加记录
        logsService.saveParentLogs(childId, userId, childId, LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.DISAPPEAR_MODEL.getModelName(), StringUtils.format("推荐人获取返佣消证{}", shopDisappear), shopDisappear.setScale(3).toString());
        disappearGetService.insetDisappearGet(userId, Constant.ShopRuleData.SHOP_COUNT_DIS, shopDisappear);
    }

    /**
     * 获取上级信息
     *
     * @param userId
     * @return
     */
    public FwUser findParent(String userId) {
        FwUser fwUser = userService.selectFwUserById(userId);
        FwUser parentUser = userService.getOne(Wrappers.<FwUser>lambdaQuery().eq(FwUser::getId, fwUser.getParentId()));
        return parentUser;
    }


    /**
     * 返消证                                      废弃
     *
     * @param userId    用户编号
     * @param disappear 消证数量
     */


    public void disappearReturnTest(String userId, BigDecimal disappear) {
        //获取用户信息
        FwUser fwUser = userService.selectFwUserById(userId);
        Integer disappearIsMore = fwUser.getDisappearIsMore();
        /**
         * 给该用户发放消证
         */
        //获取该用户钱包信息
        FwMoneys moneys = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
        BigDecimal moneysDisappear = moneys.getDisappear();//获取该用户的消证余额
        BigDecimal decimal = moneysDisappear.add(disappear);//该用户的消证余额加上发放的消证数量
        moneys.setDisappear(decimal);
        updateById(moneys);//写入数据库
        //新增该用户的消证增加记录
        logsService.saveLogs(fwUser.getId(), fwUser.getId(), LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.DISAPPEAR_MODEL.getModelName(), "消费发放", disappear.toString());

        /** 不可多级得消证,两级返佣,给上级发放消证 */
        //获取该用户的上级信息
        FwUser parentUser = userService.getOne(Wrappers.<FwUser>lambdaQuery().eq(FwUser::getId, fwUser.getParentId()));
        //给上级发放返佣的消证
        //获取上级钱包信息
        FwMoneys parentMoneys = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, parentUser.getId()));
        BigDecimal parentDisappear = parentMoneys.getDisappear();//获取上级的消证余额
        BigDecimal parentMultiply = disappear.multiply(new BigDecimal("0.1"));//将发放的消证乘以0.1,为实际发放给上级的数量
        BigDecimal parentDecimal = parentDisappear.add(parentMultiply);//上级的消证余额加上发放的消证
        parentMoneys.setDisappear(parentDecimal);
        updateById(parentMoneys);//写入数据库
        //新增上级消证增加记录
        logsService.saveLogs(parentUser.getId(), parentUser.getId(), LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.DISAPPEAR_MODEL.getModelName(), "下级" + fwUser.getUserName() + "消费返佣", parentMultiply.toString());

        /** 给上级的上级发放消证 */
        //获取上级的上级的信息
        FwUser parentUserTwo = userService.getOne(Wrappers.<FwUser>lambdaQuery().eq(FwUser::getId, parentUser.getParentId()));
        //获取上级上级的钱包信息
        FwMoneys parentMoneysTwo = getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, parentUserTwo.getId()));
        BigDecimal parentDisappearTwo = parentMoneysTwo.getDisappear();//获取上级上级的消证余额
        BigDecimal parentMultiplyTwo = parentMultiply.multiply(new BigDecimal("0.5"));//将发放上级的消证乘以0.5,为实际发放给上级上级的数量
        BigDecimal parentDecimalTwo = parentDisappearTwo.add(parentMultiplyTwo);//上级的消证余额加上发放的消证
        parentMoneysTwo.setDisappear(parentDecimalTwo);
        updateById(parentMoneysTwo);//写入数据库
        //新增上级上级消证增加记录
        logsService.saveLogs(parentUserTwo.getId(), parentUserTwo.getId(), LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.DISAPPEAR_MODEL.getModelName(), "下级" + parentUser.getUserName() + "消费返佣", parentMultiplyTwo.toString());
    }


}
